using KineBall.GameLogic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;


namespace KineBall.Rendering
{
    public class ShieldModel
    {
        public VertexBuffer VertexBuffer { get { return _vertexBuffer; } }
        private VertexBuffer _vertexBuffer;

        public IndexBuffer IndexBuffer { get { return _indexBuffer; } }
        private IndexBuffer _indexBuffer;

        public Texture2D Texture { get;  set; }

        public Matrix Scale { get; set; }

        public ShieldModel(GraphicsDevice graphicsDevice, Texture2D texture, Shield shield)
        {

            VertexPositionColorTexture[] vertexArray = new VertexPositionColorTexture[4];
            vertexArray[0] = new VertexPositionColorTexture(new Vector3(-0.5f, -0.5f, 0), Color.White, new Vector2(0, 1));
            vertexArray[1] = new VertexPositionColorTexture(new Vector3(-0.5f, 0.5f, 0), Color.White, new Vector2(0, 0));
            vertexArray[2] = new VertexPositionColorTexture(new Vector3(0.5f, 0.5f, 0), Color.White, new Vector2(1, 0));
            vertexArray[3] = new VertexPositionColorTexture(new Vector3(0.5f, -0.5f, 0), Color.White, new Vector2(1, 1));

            short[] indexArray = new short[] { 0, 1, 2, 2, 3, 0 };

            _indexBuffer = new IndexBuffer(graphicsDevice, IndexElementSize.SixteenBits, indexArray.Length, BufferUsage.None);
            _indexBuffer.SetData<short>(indexArray);

            _vertexBuffer = new VertexBuffer(graphicsDevice, VertexPositionColorTexture.VertexDeclaration, vertexArray.Length, BufferUsage.None);
            _vertexBuffer.SetData<VertexPositionColorTexture>(vertexArray);

            Texture = texture;

            Scale = Matrix.CreateScale(new Vector3(shield.Width, shield.Height, 1));

        }

        public void Draw(BasicEffect effect, Shield shield, GraphicsDevice graphicsDevice)
        {
            effect.VertexColorEnabled = true;
            effect.TextureEnabled = true;
            effect.Texture = Texture;
            effect.LightingEnabled = false;

            effect.World = Scale * Matrix.CreateTranslation(shield.position);

            effect.CurrentTechnique.Passes[0].Apply();

            graphicsDevice.SetVertexBuffer(VertexBuffer);
            graphicsDevice.Indices = IndexBuffer;
            graphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, 4, 0, 2);

            effect.VertexColorEnabled = false;
            effect.TextureEnabled = false;
        }
    }
}
